<template>
  <!-- 设备类型表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="600px"
    style="height: 400px"
    draggable
    @close="closeDialog"
    destroy-on-close
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="110">
      <el-row>
        <el-col :span="14">
          <el-form-item label="设备类型编号" prop="equipTypeCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.equipTypeCode"
              placeholder="请输入设备类型编号"
              clearable
            />

            <span v-else>{{ formData.equipTypeCode }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="14">
          <el-form-item label="设备类型名称" prop="equipTypeName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.equipTypeName"
              placeholder="请输入设备类型名称"
              clearable
            />

            <span v-else>{{ formData.equipTypeName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="14">
          <el-form-item label="设备类别" prop="equipLargeCategory">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.equipLargeCategory"
              placeholder="请选择设备类别"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in dictionaryStore.filterDictList(
                  'EquipLargeCategory'
                )"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <span v-else>{{
              dictionaryStore.filterDictName(
                "EquipLargeCategory",
                formData.equipLargeCategory
              )
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="启用状态" prop="enabled">
            <el-radio-group v-if="!props.isReadonly" v-model="formData.enabled">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
            <span v-else>{{ formData.enabled === 1 ? "启用" : "停用" }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              placeholder="请输入备注"
              clearable
            />
            <span v-else>{{ formData.remarks }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 照片 -->
      <el-form-item
        prop="imgUrl"
        style="position: relative; top: -250px; left: 250px"
      >
        <UploadImge
          :action="`${actionUrl}/system/fileCenter/uploadFile/${fileName}`"
          v-model="formData.imgUrl"
          :domainName="`${actionUrl}`"
          :isReadonly="props.isReadonly"
          :uploadStyle="{ width: '150px', height: '150px' }"
          :fileName="fileName"
        ></UploadImge>
        <el-input v-model="formData.imgUrl" style="display: none"></el-input>
        <div style="position: absolute; top: 160px; left: 15px; display: none">
          <el-button>2D</el-button> <el-button disabled>3D</el-button>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer" style="margin-top: -200px">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

// 图片地址
const actionUrl = import.meta.env.VITE_APP_BASE_API;

defineOptions({
  name: "SCAEQUIPTYPECONTENTEDIT",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);
// 定义上传图片文件夹名
const fileName = ref("scaEquiptypeFile");
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  equipTypeCode: [
    { required: true, message: "请输入设备类型编号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  equipTypeName: [
    { required: true, message: "请输入设备类型名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  equipLargeCategory: [
    { required: true, message: "请选择设备类别", trigger: "change" },
  ],
  // imgUrl: [
  //   { required: true, message: "请选择图片", trigger: "blur" },
  //   { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  // ],
  threeModelUrl: [
    // {required: true, message: "请输入设备类型编号", trigger: "blur"},
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  // sort: [{ required: true, message: "请输入序号", trigger: "blur" }],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  equipTypeCode: "",
  equipTypeName: "",
  equipLargeCategory: "",
  imgUrl: "",
  threeModelUrl: "",
  sort: "",
  enabled: 1,
  remarks: "",
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        equipTypeCode,
        equipTypeName,
        equipLargeCategory,
        imgUrl,
        threeModelUrl,
        sort,
        enabled,
        remarks,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
      } = newVal;
      Object.assign(formData, {
        ...newVal,
        id,
        equipTypeCode,
        equipTypeName,
        equipLargeCategory,
        imgUrl,
        threeModelUrl,
        sort,
        enabled,
        remarks,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.equipTypeCode = "";
  formData.equipTypeName = "";
  formData.equipLargeCategory = "";
  formData.imgUrl = "";
  formData.threeModelUrl = "";
  formData.sort = "";
  formData.enabled = 1;
  formData.remarks = "";
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
}

const loading = ref(false);

/** 设备类型保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/iotadmin/scaequiptype/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();

      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
